<template>
    <div class="app-container">
        <div class="filter-container">
            <div class="filter-item block">
                <el-date-picker
                        size="medium"
                        v-model="query.eat_date"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择订餐时间">
                </el-date-picker>
            </div>
            <el-select class="filter-item w-200" clearable v-model="query.eat_type" size="medium" placeholder="请选择订餐类型">
                <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                </el-option>
            </el-select>
            <el-select class="filter-item w-200" clearable v-model="query.is_cancel" size="medium" placeholder="状态">
                <el-option
                        v-for="item in statusOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                </el-option>
            </el-select>
            <el-select class="filter-item w-200" clearable v-model="query.is_settled" size="medium" placeholder="是否结算">
                <el-option
                        v-for="item in settleOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                </el-option>
            </el-select>
            <el-button class="filter-item" size="medium" icon="el-icon-search" @click="fetchList(true)">搜 索</el-button>
            <el-button class="filter-item" type="primary" size="medium" icon="el-icon-plus" style="float: right" @click="addBookRule" v-permission="'book-rules.store'">新 增</el-button>
        </div>
        <el-table v-loading="loading" :data="bookRules" border style="width: 100%">
            <el-table-column type="expand">
                <template slot-scope="scope">
                    <el-table :data="scope.row.prices" border :show-summary="scope.row.is_settled===1" style="width: 100%">
                        <el-table-column width="100px" label="#" align="center">
                            <template slot-scope="props" >
                                {{query.size * (query.page-1) + props.$index + 1}}
                            </template>
                        </el-table-column>
                        <el-table-column label="条目名称" align="center">
                            <template slot-scope="props">
                                {{ props.row.category.name }}
                            </template>
                        </el-table-column>
                        <el-table-column label="条目描述" align="center">
                            <template slot-scope="props">
                                {{ props.row.category.description }}
                            </template>
                        </el-table-column>
                        <el-table-column label="成本(元)" prop="total_price" align="center"></el-table-column>
                        <el-table-column v-if="scope.row.is_settled === 0 && scope.row.is_cancel === 0" label="操作" align="center">
                            <template slot-scope="props">
                                <el-button class="filter-item" type="primary" size="mini" v-permission="'book-rule-prices.update'" @click="editBookRulePrice(props.row, scope.row)">编辑</el-button>
                                <el-button class="filter-item" type="danger" size="mini" v-permission="'book-rule-prices.destroy'" @click="delBookRulePrice(props.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </template>
            </el-table-column>
            <el-table-column width="50px" label="#" align="center">
                <template slot-scope="scope" >
                    {{query.size * (query.page-1) + scope.$index + 1}}
                </template>
            </el-table-column>
            <el-table-column prop="eat_date" label="订餐时间" align="center"></el-table-column>
            <el-table-column prop="eat_type" label="订餐类型" align="center">
                <template slot-scope="scope">
                    <div v-if="scope.row.eat_type === 1">早餐</div>
                    <div v-if="scope.row.eat_type === 2">午餐</div>
                    <div v-if="scope.row.eat_type === 3">晚餐</div>
                </template>
            </el-table-column>
            <el-table-column label="菜品" align="center">
                <template slot-scope="scope">
                    <span v-for="(food,index) in scope.row.foods" :key="food.id">{{ index === 0 ? food.name : ', ' + food.name }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="count" label="订餐人数" width="150px" align="center"></el-table-column>
            <el-table-column label="总价(元)" width="150px" align="center">
                <template slot-scope="scope" >
                    {{ getTotalPrice(scope.row) }}
                </template>
            </el-table-column>
            <el-table-column label="实付总金额(元)" width="150px" align="center">
                <template slot-scope="scope">
                    {{ scope.row.is_settled === 1 ? scope.row.totalPayPrice : null }}
                </template>
            </el-table-column>
            <el-table-column label="是否启用" width="100px" align="center">
                <template slot-scope="scope" >
                    <i class="el-icon-check" v-if="scope.row.is_cancel === 0" />
                    <i class="el-icon-close" v-else />
                </template>
            </el-table-column>
            <el-table-column prop="updated_at" label="更新时间" align="center"></el-table-column>
            <el-table-column label="操作" width="450px" align="center">
                <template slot-scope="scope">
                    <el-button v-if="scope.row.is_cancel === 0" class="filter-item" type="primary" icon="el-icon-edit" size="mini" @click="editBookRule(scope.row)" v-permission="'book-rules.update'">编 辑</el-button>
                    <el-button v-if="scope.row.is_settled === 0 && scope.row.is_cancel === 0" class="filter-item" type="primary" icon="el-icon-plus" size="mini" @click="addBookRulePrice(scope.row)" v-permission="'book-rule-prices.store'">添加计费条目</el-button>
                    <el-button v-if="scope.row.is_settled === 0 && scope.row.is_cancel === 0" class="filter-item" type="danger" icon="el-icon-edit-outline" size="mini" @click="settleAccounts(scope.row.id, scope.row.cost)" v-permission="'book-rules.settle'">结算</el-button>
                    <el-button v-if="scope.row.is_settled === 0 && scope.row.is_cancel === 0" class="filter-item" type="danger" icon="el-icon-close" size="mini" @click="cancelRule(scope.row.id)" v-permission="'book-rules.destroy'">取消</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-container">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="query.page"
                    :page-sizes="[10, 20, 30, 50]"
                    :page-size="query.size"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>
        <el-dialog title="订餐规则" width="700px" :visible.sync="dialogVisible">
            <el-form :model="bookRuleForm" :rules="rules" ref="bookRuleForm" label-width="100px" class="demo-bookRuleForm">
                <el-form-item label="订餐时间" prop="eat_date">
                    <div class="block">
                        <el-date-picker
                                style="width: 90%"
                                v-model="bookRuleForm.eat_date"
                                type="date"
                                :disabled="option === 'edit'"
                                value-format="yyyy-MM-dd"
                                :picker-options="pickerOptions"
                                placeholder="选择日期时间">
                        </el-date-picker>
                    </div>
                </el-form-item>
                <el-form-item label="订餐类型" prop="eat_type">
                    <el-select :disabled="option === 'edit'" v-model="bookRuleForm.eat_type" @change="changeEatType" style="width: 90%" placeholder="请选择">
                        <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="菜品" prop="food_ids">
                    <el-select
                            v-model="bookRuleForm.food_ids"
                            multiple
                            filterable
                            allow-create
                            default-first-option
                            placeholder="请选择菜品">
                        <el-option
                                v-for="item in foods"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible=false">取消</el-button>
                <el-button type="primary" @click="submitBookRuleForm" :loading="btnLoading">保存</el-button>
            </div>
        </el-dialog>
        <el-dialog title="订餐规则价格" width="700px" :visible.sync="dialogVisible2">
            <el-form :model="bookRulePriceForm" :rules="rules2" ref="bookRulePriceForm" label-width="100px" class="demo-bookRulePriceForm">
                <el-form-item label="请选择条目" prop="category_id">
                    <el-select v-model="bookRulePriceForm.category_id" style="width: 90%" placeholder="请选择">
                        <el-option
                                v-for="item in categories"
                                :key="item.id"
                                :label="item.name"
                                :disabled="categoriesUsed.findIndex(val => {return val === item.id}) >= 0"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="成本" prop="total_price" required>
                    <el-input v-model="bookRulePriceForm.total_price" style="width: 90%" placeholder="请输入成本"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible2=false">取消</el-button>
                <el-button type="primary" @click="submitBookRulePriceForm" :loading="btnLoading2">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import { fetchBookRule, addBookRule, updateBookRule, settleBookRule, delBookRule, addBookRulePrice, updateBookRulePrice, delBookRulePrice } from '@/api/book-rule'
    import { isPriceAvailable } from '@/utils/validate'
    import { fetchFoods, fetchPriceCategories } from '@/api/data'
    export default {
      name: 'bookRules',
      data() {
        const validatePrice = (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请输入价格'))
          } else {
            if (!isPriceAvailable(value)) {
              callback(new Error('价格格式错误'))
            }
            callback()
          }
        }
        return {
          pickerOptions: {
            disabledDate(time) {
              return time.getTime() < Date.now()
            }
          },
          rules2: {
            total_price: [
              { validator: validatePrice, trigger: ['blur', 'change'] }
            ],
            category_id: [
              { required: true, message: '请选择条目', trigger: ['blur', 'change'] }
            ]
          },
          bookRulePriceForm: {
            id: '',
            total_price: '',
            category_id: '',
            rule_id: ''
          },
          categories: [],
          categoriesUsed: [],
          dialogVisible: false,
          dialogVisible2: false,
          btnLoading: false,
          btnLoading2: false,
          loading: false,
          bookRules: [],
          morningFoods: [],
          lunchFoods: [],
          dinnerFoods: [],
          foods: [],
          bookRuleForm: {
            id: '',
            eat_date: '',
            eat_type: '',
            food_ids: []
          },
          total: 0,
          query: {
            eat_date: '',
            eat_type: '',
            size: 10,
            page: 1,
            status: 1,
            rule_id: '',
            is_settle: false,
            is_settled: '',
            is_cancel: ''
          },
          queryFood: {
            status: 1,
            supply_type: []
          },
          option: '',
          option2: '',
          options: [
            {
              value: 1,
              label: '早餐'
            },
            {
              value: 2,
              label: '午餐'
            },
            {
              value: 3,
              label: '晚餐'
            }
          ],
          statusOptions: [
            {
              value: 1,
              label: '取消'
            },
            {
              value: 0,
              label: '启用'
            }
          ],
          settleOptions: [
            {
              value: 1,
              label: '已结算'
            },
            {
              value: 0,
              label: '未结算'
            }
          ],
          rules: {
            eat_type: [
              { required: true, message: '请选择订餐类型', trigger: ['blur', 'change'] }
            ],
            food_ids: [
              { required: true, message: '请选择订餐菜品', trigger: ['blur', 'change'] }
            ],
            eat_date: [
              { required: true, message: '请选择订餐日期', trigger: ['blur', 'change'] }
            ]
          },
          settleTitle: '',
          data: {}
        }
      },
      methods: {
        // 取消订餐规则
        cancelRule(id) {
          this.$confirm('该规则下的所有订单也会被取消，确定取消该订餐规则？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            delBookRule(id).then(res => {
              this.$message.success('取消成功')
              this.fetchList()
            }).catch(err => {
              this.$handleNotFound(err, '订餐规则不存在')
            })
          })
        },
        // 提交订餐规则价格表单
        submitBookRulePriceForm() {
          this.btnLoading2 = true
          this.$refs['bookRulePriceForm'].validate((valid) => {
            if (valid) {
              // 通过校验
              if (this.option2 === 'add') {
                addBookRulePrice(this.bookRulePriceForm).then(res => {
                  if (res.result === 'failed') {
                    this.$message.error(res.msg)
                  } else {
                    this.$message.success('添加成功')
                    // 直接push数据
                    res.category = {}
                    for (let i = 0; i < this.bookRules.length; i++) {
                      if (this.bookRules[i].id === res.rule_id) {
                        for (let j = 0; j < this.categories.length; j++) {
                          if (this.categories[j].id === res.category_id) {
                            res.category = this.categories[j]
                          }
                        }
                        this.bookRules[i].prices.push(res)
                      }
                    }
                    this.dialogVisible2 = false
                  }
                  this.btnLoading2 = false
                }).catch(err => {
                  this.$handleNotFound(err)
                  this.btnLoading2 = false
                })
              }
              if (this.option2 === 'edit') {
                updateBookRulePrice(this.bookRulePriceForm, this.bookRulePriceForm.id).then(res => {
                  if (res.result === 'failed') {
                    this.$message.error(res.msg)
                  } else {
                    this.$message.success('编辑成功')
                    // 直接修改数据
                    res.category = {}
                    for (let i = 0; i < this.bookRules.length; i++) {
                      if (this.bookRules[i].id === res.rule_id) {
                        for (let m = 0; m < this.categories.length; m++) {
                          if (this.categories[m].id === res.category_id) {
                            res.category = this.categories[m]
                          }
                        }
                      }
                    }
                    this.data.total_price = res.total_price
                    this.data.category = res.category
                    this.dialogVisible2 = false
                  }
                  this.btnLoading2 = false
                }).catch(err => {
                  this.$handleNotFound(err, '条目不存在')
                  this.btnLoading2 = false
                })
              }
            } else {
              this.btnLoading2 = false
            }
          })
        },
        // 添加订餐规则价格
        addBookRulePrice(row) {
          this.categoriesUsed = []
          for (let i = 0; i < row.prices.length; i++) {
            this.categoriesUsed.push(row.prices[i].category_id)
          }
          this.option2 = 'add'
          this.resetForm('bookRulePriceForm')
          this.dialogVisible2 = true
          Object.assign(this.bookRulePriceForm, this.$options.data().bookRulePriceForm)
          this.bookRulePriceForm.rule_id = row.id
        },
        // 编辑订餐规则价格
        editBookRulePrice(row, ruleRow) {
          this.categoriesUsed = []
          for (let i = 0; i < ruleRow.prices.length; i++) {
            this.categoriesUsed.push(ruleRow.prices[i].category_id)
          }
          if (this.$refs['bookRulePriceForm'] !== undefined) {
            this.$refs['bookRulePriceForm'].clearValidate()
          }
          this.option2 = 'edit'
          this.dialogVisible2 = true
          Object.existAssign(this.bookRulePriceForm, row)
          this.data = row
        },
        // 删除订餐规则价格
        delBookRulePrice(row) {
          this.$confirm('确定删除该订餐价格规则?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            delBookRulePrice(row.id).then(res => {
              this.$message.success('删除成功')
              // 直接移除
              for (let i = 0; i < this.bookRules.length; i++) {
                if (this.bookRules[i].id === row.rule_id) {
                  for (let j = 0; j < this.bookRules[i].prices.length; j++) {
                    if (this.bookRules[i].prices[j].id === row.id) {
                      this.bookRules[i].prices.splice(j, 1)
                    }
                  }
                }
              }
            }).catch(err => {
              this.$handleNotFound(err, '条目不存在')
            })
          })
        },
        // 提交
        submitBookRuleForm() {
          this.btnLoading = true
          this.$refs['bookRuleForm'].validate((valid) => {
            if (valid) {
              // 通过校验
              if (this.option === 'add') {
                addBookRule(this.bookRuleForm).then(res => {
                  if (res.result === 'failed') {
                    this.$message.error(res.msg)
                  } else {
                    this.$message.success('添加成功')
                    this.getSchoolInfo()
                    this.dialogVisible = false
                  }
                  this.btnLoading = false
                }).catch(err => {
                  this.$handleNotFound(err)
                  this.btnLoading = false
                })
              }
              if (this.option === 'edit') {
                updateBookRule(this.bookRuleForm, this.bookRuleForm.id).then(res => {
                  if (res.result === 'failed') {
                    this.$message.error(res.msg)
                  } else {
                    this.$message.success('编辑成功')
                    this.getSchoolInfo()
                    this.dialogVisible = false
                  }
                  this.btnLoading = false
                }).catch(err => {
                  this.$handleNotFound(err, '订餐规则不存在')
                  this.btnLoading = false
                })
              }
            } else {
              this.btnLoading = false
            }
          })
        },
        // 切换订餐类型
        changeEatType() {
          this.bookRuleForm.food_ids = []
          if (this.bookRuleForm.eat_type === 1) {
            this.foods = this.morningFoods
          }
          if (this.bookRuleForm.eat_type === 2) {
            this.foods = this.lunchFoods
          }
          if (this.bookRuleForm.eat_type === 3) {
            this.foods = this.dinnerFoods
          }
        },
        // 添加订餐规则
        addBookRule() {
          this.foods = []
          this.resetForm('bookRuleForm')
          this.dialogVisible = true
          this.option = 'add'
          Object.assign(this.bookRuleForm, this.$options.data().bookRuleForm)
        },
        // 编辑订餐规则
        editBookRule(row) {
          if (this.$refs['bookRuleForm'] !== undefined) {
            this.$refs['bookRuleForm'].clearValidate()
          }
          this.bookRuleForm.food_ids = []
          this.option = 'edit'
          Object.existAssign(this.bookRuleForm, row)
          this.changeEatType()
          this.dialogVisible = true
          for (let i = 0; i < row.foods.length; i++) {
            this.bookRuleForm.food_ids.push(row.foods[i].id)
          }
        },
        // 结算
        settleAccounts(ruleId, cost) {
          if (cost <= 0) {
            this.settleTitle = '总价为0时，计算餐标订单的实际支付价格也会为0，并且结算后，该订餐规则下的条目将不可修改，确定结算?'
          } else {
            this.settleTitle = '一经结算，该订餐规则下的条目将不可修改，确定结算?'
          }
          this.$confirm(this.settleTitle, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            // 已结算的订餐规则不能进行操作
            this.query.is_settle = true
            this.query.id = ruleId
            settleBookRule(this.query, ruleId).then(res => {
              if (res.result === 'failed') {
                this.$message.error(res.msg)
              } else {
                this.$message.success('结算成功')
                this.fetchList()
              }
            }).catch(err => {
              this.$handleNotFound(err, '订餐规则不存在')
            })
          })
        },
        // 订餐规则列表
        fetchList(resetPage = false) {
          this.loading = true
          if (resetPage === true) {
            this.query.page = 1
          }
          fetchBookRule(this.query).then(res => {
            this.bookRules = res.data
            this.total = res.meta.total
            this.loading = false
          })
        },
        // 条目列表
        fetchPriceCategories() {
          fetchPriceCategories().then(res => {
            this.categories = res.categories
          })
        },
        // 获取当前学校id
        getSchoolInfo() {
          this.fetchList()
          this.fetchFoodList()
          this.fetchPriceCategories()
        },
        fetchFoodList() {
          this.morningFoods = []
          this.lunchFoods = []
          this.dinnerFoods = []
          fetchFoods().then(res => {
            for (let i = 0; i < res.foods.length; i++) {
              if (res.foods[i].supply_type === 1 || res.foods[i].supply_type === 12 || res.foods[i].supply_type === 13 || res.foods[i].supply_type === 123) {
                this.morningFoods.push(res.foods[i])
              }
              if (res.foods[i].supply_type === 2 || res.foods[i].supply_type === 12 || res.foods[i].supply_type === 23 || res.foods[i].supply_type === 123) {
                this.lunchFoods.push(res.foods[i])
              }
              if (res.foods[i].supply_type === 3 || res.foods[i].supply_type === 13 || res.foods[i].supply_type === 23 || res.foods[i].supply_type === 123) {
                this.dinnerFoods.push(res.foods[i])
              }
            }
          })
        },
        // 重置表单验证
        resetForm(formName) {
          // 第一次新增数据时为空对象undefined
          if (this.$refs[formName] !== undefined) {
            this.$refs[formName].resetFields()
          }
        },
        // 重置搜索
        resetSearch() {
          this.query.eat_date = ''
          this.query.eat_type = ''
          this.fetchList(true)
        },
        handleSizeChange(size) {
          this.query.size = size
          this.fetchList()
        },
        handleCurrentChange(page) {
          this.query.page = page
          this.fetchList()
        },
        getTotalPrice(row) {
          let cost = 0
          for (let i = 0; i < row.prices.length; i++) {
            cost += row.prices[i].total_price
          }
          return cost
        }
      },
      created() {
        this.getSchoolInfo()
      }
    }
</script>

<style scoped>
    .el-icon-check{
        color: green;
    }
    .el-icon-close{
        color: red;
    }
</style>
